import Taro from "@tarojs/taro";
import InterceptorManager from './InterceptorManager'
import utils from './utils'

class WxRequest {
	constructor(defaults) {
        this.defaults = Object.assign({
            baseURL: ''
        }, defaults)
        
        this.interceptors = {
            request: new InterceptorManager(),
            response: new InterceptorManager(),
            downloadFile: new InterceptorManager()
        }
    }

    _handleConfig() {
        let config = arguments[0]

        // 判断参数类型，如果第一个参数为字符串则赋值于 url，第二个参数为 config 配置
        if (typeof config === 'string') {
            config = Object.assign({
                url: arguments[0]
            }, arguments[1])
        }

        // 合并参数
        config = Object.assign({}, this.defaults, config)

        // 处理 url 兼容绝对路径、相对路径
        if (config.baseURL && !utils.isAbsoluteURL(config.url)) {
            config.url = utils.combineURLs(config.baseURL, config.url)
        }

        return config
    }

    _http(config) {
        return new Promise((resolve, reject) => {
            config.success = response => {
                response.config = config
                return resolve(response)
            }
            config.fail = err => {
                err.config = config
                return reject(err)
            }
            Taro.request(config)
        })
    }

    request() {
        let config = this._handleConfig(...arguments)

        let chain = [this._http, undefined]
        let promise = Promise.resolve(config)

        this.interceptors.request.forEach(interceptor => {
            chain.unshift(interceptor.fulfilled, interceptor.rejected)
        })

        this.interceptors.response.forEach(interceptor => {
            chain.push(interceptor.fulfilled, interceptor.rejected)
        })
        

        while (chain.length) {
            promise = promise.then(chain.shift(), chain.shift())
        }

        return promise
    }

    all(promises) {
        return Promise.all(promises)
    }
}

export default WxRequest